package com.example.excel.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 设置切面 执行具体方法选择的数据源
 *
 * @author shigen
 */
@Aspect
@Component
@Slf4j
public class DataSourceAop {

    /**
     * 需要读的方法,切面 选择service包及其子包中以select、list开头的方法，并排除带有@Master注解的方法
     */
    @Pointcut("(execution(* com.example.excel.Service.*.select*(..)) " +
        "|| execution(* com.example.excel.Service..*.get*(..)))" +
        "|| execution(* com.example.excel.Service..*.find*(..))" +
        "|| execution(* com.example.excel.Service..*.list*(..))"
    )
    public void readPointcut() {

    }

    /**
     * 写切面
     */
    @Pointcut("execution(* com.example.excel.Service..*.insert*(..))" +
        "|| execution(* com.example.excel.Service..*.save*(..))" +
        "|| execution(* com.example.excel.Service..*.add*(..))" +
        "|| execution(* com.example.excel.Service..*.update*(..))" +
        "|| execution(* com.example.excel.Service..*.edit*(..))" +
        "|| execution(* com.example.excel.Service..*.delete*(..))" +
        "|| execution(* com.example.excel.Service..*.remove*(..))")
    public void writePointcut() {

    }

    @Before("readPointcut()")
    public void read() {
        log.info("进入读切点");
        DataSourceContextHolder.slave();
    }

    @Before("writePointcut()")
    public void write() {
        log.info("进入写切点");
        DataSourceContextHolder.master();
    }

    @After("readPointcut()")
    public void readAfter() {
        DataSourceContextHolder.clear();
    }

    @After("writePointcut()")
    public void writeAfter() {
        DataSourceContextHolder.clear();
    }
}

